//
//  PhotoCollectionViewController.swift
//  TwERP2017
//
//  Created by Li Xiangyang on 29/06/2017.
//  Copyright © 2017 Li Xiangyang. All rights reserved.
//

import UIKit


class PhotoCollectionViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    var gdVTC: DetailViewController!
    var currentIndex: Int = 0
    let picker = UIImagePickerController()
    
    @IBOutlet var photosView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false
        picker.delegate = self as! UIImagePickerControllerDelegate & UINavigationControllerDelegate
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    func deletePhoto(afile: TwERPAttachedFile) -> () {
        if !gdVTC.gongdanBeginEdit(){
            let alert =  UIAlertController(title: "提示", message: "工单不可修改!", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){}
            return
        }
        
        var tempItems: [TwERPAttachedFile] = gdVTC.gongdan?.attachedFiles as! [TwERPAttachedFile]
        
        
        for index in 0...tempItems.count-1 {
            if tempItems[index].fileDescription == afile.fileDescription{
                tempItems.remove(at: index)
            }
        }
        gdVTC.gongdan?.attachedFiles = tempItems
    }


    // MARK: UICollectionViewDelegate

    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let aFiles = gdVTC.gongdan?.photoFiles()
        return aFiles!.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "photo file")!
        let aFiles: [TwERPAttachedFile] = gdVTC.gongdan!.photoFiles() as! [TwERPAttachedFile]
        let afile: TwERPAttachedFile = aFiles[indexPath.row]
       
        cell.textLabel?.text = afile.fileDescription
        cell.detailTextLabel?.text =  afile.fileDate
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        currentIndex = indexPath.row
        //presentReading()
        
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        
        let aFiles: [TwERPAttachedFile] = gdVTC.gongdan!.photoFiles() as! [TwERPAttachedFile]
        let afile: TwERPAttachedFile = aFiles[indexPath.row]
        deletePhoto(afile: afile)
        
        tableView.deleteRows(at: [indexPath], with: .fade)

    }
    
    @IBAction func takePhoto(_ sender: Any) {
        if gdVTC.gongdan == nil {
            let alert =  UIAlertController(title: "提示", message: "请先生成工单!", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){print("hello")}
            return
        }
        
              picker.allowsEditing = false
            picker.sourceType = UIImagePickerControllerSourceType.camera
    
            picker.cameraCaptureMode = .photo
            picker.modalPresentationStyle = .fullScreen
            present(picker,
                    animated: true,
                    completion: nil)
    }
    //MARK: - Delegates
    //What to do when the picker returns with a photo
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        if !gdVTC.gongdanBeginEdit(){
            let alert =  UIAlertController(title: "提示", message: "工单不可修改!", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){}
            return
        }

          let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2
        let directory = TwERPAttachedFile.localDirectory()
        
        let imgFilePath = String(format: "%@/tw_image%d-%d.png", directory!,(gdVTC.gongdan?.entityId)!,(gdVTC.gongdan?.attachedFiles.count)!+1)
        let imgUrl = NSURL.fileURL(withPath: imgFilePath)
   
        do {
            try UIImagePNGRepresentation(chosenImage)?.write(to: imgUrl, options: Data.WritingOptions.atomicWrite)
            
        } catch _ {
        }
  
        let  af = TwERPAttachedFile(newId: () )
        af?.fileDescription = String(format: "Photo%d", (gdVTC.gongdan?.attachedFiles.count)!+1)
        af?.url = imgUrl
        af?.type = "image"
        
        gdVTC.gongdan?.addAttachedFile(af)
 
        // update attached file
        self.photosView.reloadData()
 
        dismiss(animated: true, completion: nil) //5
    }
    //What to do if the image picker cancels.
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true,
                completion: nil)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        if (segue.identifier == "Gongdan Image" ){
            let vs = segue.destination as! TwERPGdImageDisplayViewController
            vs.gongdan = self.gdVTC.gongdan!
            vs.imgNo = Int32(currentIndex-1)
            return
        }

    }
}
